<template>
  <div class="album">
    <h1 class="title">{{ album.name }}-相册详情</h1>
    <div class="box">
      <div class="wrapper">
        <div class="top">
          <template v-if="!isBatch">
            <el-button type="primary" size="medium" @click="edit"><svg-icon icon-class="upload-img" /> 上传照片</el-button>
            <el-button size="medium" @click="isBatch = true">批量管理</el-button>
          </template>
          <template v-else>
            <div class="batch">
              <el-checkbox v-model="checkedAll" @change="checkAll">全部</el-checkbox>
              <el-button class="button first" icon="el-icon-delete" size="small" @click="deleteMany">批量删除</el-button>
              <el-button class="button" size="small" @click="movePics"><svg-icon icon-class="img-move" />移动到相册</el-button>
              <el-button type="text" @click="isBatch = false">完成管理</el-button>
            </div>
          </template>
        </div>
        <div v-if="album.albumDetails.length === 0" class="none">
          <p class="img"><img src="../../../assets/images/none-album.png" alt="暂无相册"></p>
          <h4>暂无图片</h4>
          <p>您还没有上传图片哦～</p>
        </div>
        <ul v-else class="list">
          <li v-for="(pic, i) in dialogForm.albumDetails" :key="pic.id">
            <div class="img-box">
              <div v-if="isBatch" class="checkbox"><input v-model="pic.selected" type="checkbox" @change="checkItem(pic.selected)"></div>
              <el-image style="width: 200px; height: 200px" :src="qnPath(pic.image)" fit="fit" :preview-src-list="previewPics" lazy>
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </div>
            <div class="info">
              <p><el-input v-model.trim="pic.name" size="mini" clearable @blur="blurToChangePicName(i, pic.name)" /></p>
              <div>
                <el-button type="text" class="del" @click="deletePicDirect(pic)">删除</el-button>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- dialog -->
    <el-dialog v-el-drag-dialog class="dialog-photo" width="900px" :visible.sync="dialogvisible">
      <h3 slot="title">上传照片</h3>
      <div class="dialog-body">
        <el-form ref="dialogForm" :model="dialogForm" label-width="100px">
          <el-form-item class="name-ipt" prop="name" label="相册名称：" :rules="[{ required: true, message: '请输入相册名称', trigger: 'blur' }]">
            <el-input v-model.trim="dialogForm.name" size="medium" placeholder="请输入相册名称" clearable />
          </el-form-item>
          <el-form-item prop="name" label="上传照片：">
            <div class="pic-box">
              <div v-for="(pic, i) in dialogFormPhotosBak" :key="pic.id" class="pic">
                <div class="img">
                  <el-image style="width: 120px; height: 95px" :src="qnPath(pic.image)" fit="fill" lazy>
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" />
                    </div>
                  </el-image>
                  <p class="img-del" @click="delPic(pic, i)"><i class="el-icon-delete" /></p>
                </div>

                <el-input v-model.trim="pic.name" size="mini" clearable />
              </div>
              <image-upload :size="4096" imgname="相册图片" :multiple="true" @onSuccess="picUploadSuc">
                <p><i class="el-icon-plus" /><span>添加照片</span></p>
              </image-upload>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="btns">
        <el-button size="medium" type="primary" @click="dialogOK('dialog')">确 定</el-button>
        <el-button size="medium" @click="goBack">返 回</el-button>
      </div>
    </el-dialog>
    <!-- move-dialog -->
    <el-dialog v-el-drag-dialog class="dialog-photo move-dialog" width="900px" :visible.sync="movedialogvisible">
      <h3 slot="title">移动到相册</h3>
      <div class="dialog-body">
        <ul class="album-list">
          <li v-for="pic in albumListSumarry" :key="pic.id" :class="{'on': pic.id === moveTarget }"><el-radio-group v-model="moveTarget" class="radio-group"><el-radio class="radio" :label="pic.id"><img :src="qnPath(pic.image)" :alt="pic.name"><span class="name text-ellipsis">{{ pic.name }}</span></el-radio></el-radio-group></li>
        </ul>
      </div>
      <div slot="footer" class="btns">
        <el-button size="medium" type="primary" @click="moveDialogOK">确 定</el-button>
        <el-button size="medium" @click="moveGoBack">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ImageUpload from '@/components/ImagesUpload';
import { mapGetters } from 'vuex';
import { updateAlbum, deleteAlbum, deletePic, getAlbumDetails, movePicToAlbum } from '@/api/shop';
import { deleteQnImg } from '@/api/qiniu';
export default {
  name: 'AlbumDetail',
  components: {
    ImageUpload
  },
  data() {
    return {
      moveTarget: '',
      albumListSumarry: [], // 从首页传过来的相册列表
      movedialogvisible: false, // 移动到相册弹窗
      id: '',
      album: { albumDetails: [] },
      delQnImageList: [],
      dialogvisible: false,
      isBatch: false, // 批量管理
      previewPics: [],
      checkedAll: false,
      checkedCount: 0,
      dialogForm: {
        name: '',
        albumDetails: []
      },
      dialogFormPhotosBak: [],
      deletePicsBak: [],
      addPicsBak: [], // 暂存上传的图片
      uploadTarget: '' // 图片上传相册ID
    };
  },
  computed: {
    ...mapGetters(['qiniuResUrl', 'shopInfo'])
  },
  watch: {
    checkedCount(value) {
      this.checkedAll = value === this.dialogForm.albumDetails.length;
    }
  },
  created() {
    this.albumListSumarry = JSON.parse(this.$route.query.list);
    this.getAlbumDetails();
  },
  activated() {
    this.albumListSumarry = JSON.parse(this.$route.query.list);
    this.getAlbumDetails();
  },
  methods: {
    moveDialogOK() {
      if (!this.moveTarget) {
        this.$message({
          type: 'warning',
          message: '请先选择移动的目标相册'
        });
        return;
      }
      const albumDetails = [];
      this.dialogForm.albumDetails.map(pic => {
        if (pic.selected) return albumDetails.push({ id: pic.id, albumId: this.moveTarget });
      });
      new Promise((resolve, reject) => {
        movePicToAlbum({ albumDetails }).then(({ data }) => {
          this.$message({
            type: 'success',
            message: '移动成功!',
            duration: 1500,
            onClose: () => {
              this.$router.push({ name: 'Album' });
              this.getAlbumDetails();
              this.isBatch = false;
              this.checkedCount = 0;
            }
          });
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
      this.movedialogvisible = false;
    },
    moveGoBack() {
      this.moveTarget = '';
      this.movedialogvisible = false;
    },
    movePics() {
      if (this.checkedCount === 0) {
        this.$message({
          type: 'warning',
          message: '请先选择要移动的图片'
        });
        return;
      }
      this.movedialogvisible = true;
    },
    checkAll(value) {
      this.checkedCount = value ? this.dialogForm.albumDetails.length : 0;
      this.dialogForm.albumDetails.forEach(pic => {
        pic.selected = value;
      });
    },
    checkItem(val) {
      val ? this.checkedCount++ : this.checkedCount--;
    },
    blurToChangePicName(i, newName) {
      const oldName = this.album.albumDetails[i].name;
      if (oldName !== newName) {
        this.dialogOK();
      }
    },
    deleteMany() {
      this.$confirm('此操作将永久删除所选图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idArr = [];
        this.dialogForm.albumDetails.map(pic => {
          if (pic.selected) return idArr.push(pic.id);
        });

        new Promise((resolve, reject) => {
          deletePic({ id: idArr.join(',') }).then(({ data }) => {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1500,
              onClose: () => {
                this.getAlbumDetails();
                this.isBatch = false;
                this.checkedCount = 0;
              }
            });
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getAlbumDetails() {
      const id = this.$route.params.id;
      new Promise((resolve, reject) => {
        getAlbumDetails({ id }).then(({ data }) => {
          this.album = data;
          const details = [];
          this.dialogForm = JSON.parse(JSON.stringify(data));
          data.albumDetails.map(pic => {
            pic.selected = false;
            this.previewPics.push(this.qnPath(pic.image));
            details.push(pic);
          });
          this.dialogForm.albumDetails = details;
          this.checkedCount = 0;
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    deletePicDirect(pic) {
      this.$confirm('此操作将永久删除图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          deletePic({ id: pic.id }).then(({ data }) => {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            });
            this.delQnImageList.push(pic.image);
            this.getAlbumDetails();
            this.dialogFormPhotosBak = data.albumDetails;
            this.deleteQnImgSingle(pic.image);
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deletePic() {
      const arr = [];
      this.deletePicsBak.map(pic => {
        arr.push(pic.id);
      });
      new Promise((resolve, reject) => {
        deletePic({ id: arr.join(',') }).then(({ data }) => {
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    deleteQnImgSingle(path) {
      new Promise((resolve, reject) => {
        deleteQnImg({ path }).then(({ data }) => {
          console.log('删除七牛云图片' + path + '成功');
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    edit() {
      this.dialogFormPhotosBak = [];
      this.addPicsBak = [];
      this.dialogForm = {
        name: '',
        albumDetails: []
      };
      const copyedAlbum = JSON.parse(JSON.stringify(this.album));
      this.dialogForm = copyedAlbum;
      copyedAlbum.albumDetails.map(pic => {
        this.dialogFormPhotosBak.push(pic);
      });
      this.dialogvisible = true;
    },
    delAlbum(id) {
      this.$confirm('此操作将永久删除该相册, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          deleteAlbum({ id }).then(({ data }) => {
            this.$message({
              type: 'success',
              message: '删除相册成功!',
              duration: 1500
            });
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    goBack() {
      this.dialogvisible = false;
      this.dialogForm = this.album;
      this.dialogFormPhotosBak = [];
      this.deletePicsBak = [];
    },
    dialogOK(type = '') {
      let msg = '';
      if (type === 'dialog') {
        msg = '编辑相册成功';
        this.dialogForm.albumDetails = this.dialogFormPhotosBak;
      } else {
        msg = '修改成功';
      }
      const { name, albumDetails } = this.dialogForm;
      const shopId = this.shopInfo.id;
      if (!name) {
        this.$message({
          type: 'warning',
          message: '请输入相册名'
        });
        return;
      }
      new Promise((resolve, reject) => {
        updateAlbum({ id: this.dialogForm.id, name, shopId, albumDetails }).then(({ data }) => {
          this.$message({
            type: 'success',
            message: msg,
            duration: 1500,
            onClose: () => {
              this.goBack();
              this.getAlbumDetails();
              this.dialogvisible = false;
            }
          });
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    picUploadSuc(res) {
      const picNameArr = res.replace(this.qiniuResUrl, '').split('-');
      picNameArr.shift();
      const picName = picNameArr.join('');
      this.dialogFormPhotosBak.push({ name: picName, image: res, shopId: this.shopInfo.id, albumId: this.dialogForm.id, id: '' });
      this.addPicsBak.push(res);
    },
    delPic(pic, index) { // 只是暂时将页面上的图片删除，不显示
      this.dialogFormPhotosBak.splice(index, 1);
      this.deletePicsBak.push(pic);
    }
  }
};
</script>
<style lang="scss" scoped>
input[type="checkbox"]{
    display: inline-block;
    position: relative;
    border: 1px solid #DCDFE6;
    border-radius: 2px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 18px;
    height: 18px;
    background-color: #FFF;
    -webkit-appearance:none;
    z-index: 1;
    outline: none;
    -webkit-transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
    transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
    cursor: pointer;
    &:hover{
          border-color: #409EFF;
    }
    &:checked{
      background-color: #409EFF;
      border-color: #409EFF;
      &::after{
        transform: rotate(45deg) scaleY(1);
      }
    }
    &::after{
      display: block;
      -webkit-box-sizing: content-box;
      box-sizing: content-box;
      content: "";
      border: 1px solid #fff;
      border-left: 0;
      border-top: 0;
      height: 7px;
      left: 6px;
      position: absolute;
      top: 3px;
      -webkit-transform: rotate(45deg) scaleY(0);
      transform: rotate(45deg) scaleY(0);
      width: 3px;
      -webkit-transition: -webkit-transform .15s ease-in .05s;
      transition: -webkit-transform .15s ease-in .05s;
      transition: transform .15s ease-in .05s;
      transition: transform .15s ease-in .05s, -webkit-transform .15s ease-in .05s;
      transition: transform .15s ease-in .05s,-webkit-transform .15s ease-in .05s;
      -webkit-transform-origin: center;
      transform-origin: center;
    }
}
.album{
	background-color: #fff;
	width: 100%;
	border-radius: 2px;
	font-size: $fontSizeBase;
	color: $textColorBase;
	line-height: calc(22/ 14);
	.box{
		padding-top: 50px;
		min-height: calc(100vh - 255px);
		display: flex;
		align-items: flex-start;
		justify-content: center;
	}
  .none{
    width: 100%;
		min-height: calc(100vh - 255px - 85px);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    h4{
      font-size: 18px;
      font-weight: bolder;
      color: #3C4353;
      margin: 10px 0 ;
    }
  }
	.wrapper{
		display: flex;
		align-items: flex-start;
		flex-direction: column;
		width: 80%;
		max-width: 1170px;
	}
	.top{
    width: 100%;
		span{
			margin-left: 15px;
		}
	}
  .batch{
    width: 100%;
    background-color: #F2F7FF;
    height: 70px;
    display: flex;
    align-items: center;
    padding-left: 20px;
    /deep/ .el-checkbox__inner{
      width: 18px;
      height: 18px;
      &::after{
        left: 6px;
        top: 3px;
      }
    }
    .button{
      margin-left: 20px;
      svg{
        font-size: 14px;
        margin-right: 6px;
      }
      &:hover{
        background-color: #fff;
        svg{
          color: #409EFF;
        }
      }
      &.first{
        margin-left: 40px;
      }
    }
  }
	.list{
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		flex-wrap: wrap;
		margin-top: 30px;
		li{
			max-width: 240px;
			margin-bottom: 25px;
      margin-right: 25px;
      &:nth-child(5n){
        margin-right: 0;
      }
		}
	}
	.img-box{
		width: 210px;
		height: 210px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid $borderColor;
    position: relative;
	}
  .checkbox{
    position: absolute;
    left: -1px;
    top: -1px;
    line-height: 1;
    z-index: 2;
  }
	.info{
		display: flex;
		align-items: center;
		justify-content: space-between;
		max-width: 210px;
    padding: 0 5px;
		&>p{
			flex: 0 0 80%;
			max-width: 80%;
			display: flex;
			align-items: center;
		}
    /deep/ input{
      border-color: transparent;
      padding-left: 0;
      &:focus{
        border-color: $borderColor;
      }
    }
		.del{
			color: $textColorDark;
		}
	}
}

.dialog-photo{
	.h3{
		color: $textColorDark;
	}
	/deep/ .el-dialog__body,/deep/ .el-dialog__footer{
		padding-right: 50px;
	}
	/deep/ .el-dialog__body{
		border-top: 1px solid $borderColor;
		padding-bottom: 10px;
	}
	/deep/ .el-dialog__footer{
		padding-top: 0;
	}
	.name-ipt{
		max-width: 45%;
	}
	.pic-box{
		height: 285px;
		display: flex;
		align-items: flex-start;
		flex-wrap: wrap;
		overflow-y: scroll;
		padding: 12px;
		border: 1px solid $borderColor;
	}
	.pic,.upload{
		width: 120px;
		flex: 0 0 120px;
		margin-right: 20px;
	}
	.pic{
		display: flex;
		flex-direction: column;
		margin-bottom: 20px;
		&:nth-child(5n){
			margin-right: 0;
		}
		/deep/ .el-input{
			line-height: 25px;
		}
		/deep/ .el-input__inner{
			height: 25px;
      line-height: 25px;
			padding: 0 10px;
			border-radius: 2px;
		}
	}
	.img{
		position: relative;
		height: 95px;
		&:hover .img-del{
			display: block;
		}
	}
	.img-del{
		display: none;
		width: 100%;
		height: 24px;
		line-height: 24px;
		text-align: center;
		background-color: rgba(0,0,0, 0.3);
		position: absolute;
		bottom: 0;
		left: 0;
		transition: all 0.2s ease;
		cursor: pointer;
		.el-icon-delete{
			color: #fff;
		}
	}
	.upload{
		height: 120px;
		background-color: #F9FBFC;
		border: 1px solid $borderColor;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-right: 0;
		.el-icon-plus,span{
			display: block;
			text-align: center;
		}
		.el-icon-plus{
			font-size: 24px;
			color: $mainColor;
		}
		span{
			font-size: 12px;
			color: #A8ABB8;
		}
	}
	.btns{
		text-align: left;
		padding-left: 100px;
	}
}
.move-dialog{
  .album-list{
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    justify-content: flex-start;
    height: 250px;
    overflow-y: scroll;
    li{
      box-sizing: border-box;
      padding: 5px;
      border: 1px solid $borderColor;
      flex: 0 0 30%;
      margin-right: 5%;
      border-radius: 3px;
      margin-bottom: 20px;
      &.on{
        border-color: #409EFF;
      }
      &:nth-child(3n){
        margin-right: 0;
      }
      img{
        display: inline-block;
        width: 50px;
        height: 50px;
        margin-right: 5px;
      }
      .name{
        display: inline-block;
        max-width: calc(100% - 60px);
      }
    }
    .radio-group,.radio{
      width: 100%;
    }
    /deep/ .el-radio__label{
      padding-left: 0;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
  }
  /deep/ .el-radio__input{
    opacity: 0;
    outline: 0;
    position: absolute;
    margin: 0;
    width: 0;
    height: 0;
    z-index: -1;
  }
}
</style>
